# MACD指标计算
# 计算12日和26日的EMA数据
# 计算12日EMA:EMA(12) = 2/(12+1) * 今日收盘价(12) + 11/(12+1) * 昨日EMA(12)
# 计算26日EMA:EMA(26) = 2/(26+1) * 今日收盘价(26) + 25/(26+1) * 昨日EMA(26)
# 计算DEA:DEA = 2/(9+1) * 今日DIFF + 8/(9+1) * 昨日DEA
# 计算MACD：MACD = 2 * (DIFF-DEA)
# 注意：上市首日DIFF、DEA、MACD均为0，次日的EMA均按照上市首日的收盘价计算

def MACD(symbol, start_time, end_time):
    '''计算MACD指标
        输入参数：symbol <- str      标的代码 （2005年以前上市的不可用）
                start_time <- str  起始时间
                end_time <- str    结束时间
        输出数据：
                macd <- dataframe  macd指标，包括DIFF、DEA、MACD

    '''
    # 取历史数据，取到上市首日
    data = history(symbol=symbol, frequency='1d', start_time='2005-01-01', end_time=end_time, fields='symbol,bob,close',
                   df=True)
    # 将数据转化为dataframe格式
    data['bob'] = data['bob'].apply(lambda x: x.strftime('%Y-%m-%d')).tolist()

    # 计算EMA(12)和EMA(16)
    data['EMA12'] = data['close'].ewm(alpha=2 / 13, adjust=False).mean()
    data['EMA26'] = data['close'].ewm(alpha=2 / 27, adjust=False).mean()

    # 计算DIFF、DEA、MACD
    data['DIFF'] = data['EMA12'] - data['EMA26']
    data['DEA'] = data['DIFF'].ewm(alpha=2 / 10, adjust=False).mean()
    data['MACD'] = 2 * (data['DIFF'] - data['DEA'])

    # 上市首日，DIFF、DEA、MACD均为0
    data['DIFF'].iloc[0] = 0
    data['DEA'].iloc[0] = 0
    data['MACD'].iloc[0] = 0

    # 按照起止时间筛选
    MACD = data[(data['bob'] >= start_time)]

    return MACD

# 测试一下
a = MACD(symbol = 'DCE.y2101',start_time = '2020-01-01',end_time = '2020-10-22')